<?php
class ModuleService extends BaseDbService
{
	public function __construct()
	{
		$this->dao	= new ModuleDao();
	}
	
	public function get($id)
	{
		$info	= $this->dao->get($id);
		if(!$info)
		{
			return false;
		}
		$info['info']	= json_decode($info['info'],true);
		$info['info']['otherkeyword']	= C('CommonFunction')->getKeywordList($info['info']['otherkeyword']);
		if(!empty($info['data']))
		{
			$info['data']	= json_decode($info['data'],true);
		}
		return $info;
	}
	
	public function add($data)
	{
		if(!array_key_exists('update_time',$data['info']) && array_key_exists('data', $data))
		{
			$data['info']['update_time']	= time();
		}
		$data['info']		= json_encode($data['info']);
		if(array_key_exists('data', $data))
		{
			$data['data']		= json_encode($data['data']);
		}
		if(!array_key_exists('created', $data))
		{
			$data['created']	= date('Y-m-d H:i:s');
		}
		return $this->dao->add($data);
	}
	
	public function update($id,$data)
	{
		if(array_key_exists('data', $data))
		{
			if(!array_key_exists('info',$data))
			{
				$tmp				= $this->get($id);
				if(!$tmp)
				{
					return false;
				}
				$data['info']	= $tmp['info'];
			}
			$data['info']['update_time']	= time();
			$data['data']					= json_encode($data['data']);
		}
		if(array_key_exists('info', $data))
		{
			if(is_array($data['info']['otherkeyword']))
			{
				$data['info']['otherkeyword']	= implode(',',$data['info']['otherkeyword']);
			}
			$data['info']					= json_encode($data['info']);
		}
		$result			= $this->dao->update($id, $data);
		return $result;
	}
	
	public function getListByPosition($position)
	{
		$condition['where']['expression'] 	= 'position = '.$position;
		$condition['orderby'] 				= 'orderby DESC';
		$list		= $this->dao->fetchRows($condition);
		if($list)
		{
			foreach($list as &$lv)
			{
				$lv['info']	= json_decode($lv['info'],true);
				$lv['info']['otherkeyword']	= C('CommonFunction')->getKeywordList($lv['info']['otherkeyword']);
				if(!empty($lv['data']))
				{
					$lv['data']	= json_decode($lv['data'],true);
				}
			}
		}
		return $list;
	}
	
	public function delByPosition($position)
	{
		return $this->dao->deleteRows(array('expression'=>'position='.$position));
	}
}